package com.bike.controller.system;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bike.controller.BaseController;
import com.bike.entity.SysRole;
import com.bike.entity.SysUser;
import com.bike.po.ParamPoAdmin;
import com.bike.service.impl.SystemServiceImpl;
import com.bike.util.Md5Util;
import com.bike.util.PageData;
import com.bike.util.TimeManager;

@Controller
@RequestMapping("login")
public class LoginController extends BaseController{
	@Autowired
	private SystemServiceImpl systemServiceImpl;
 
	@RequestMapping("toLogin")
	public String index(HttpServletRequest request,Model model,ParamPoAdmin paramPo
			,@RequestParam(defaultValue="1")int page){
		return "/system/login";
	}
	@RequestMapping("logout")
	public String loginOut(HttpServletRequest request,Model model,ParamPoAdmin paramPo
			,@RequestParam(defaultValue="1")int page){
		request.getSession().removeAttribute("role");
		 request.getSession().removeAttribute("user");
		return "/system/login";
	}
	@RequestMapping("doLogin")
	@ResponseBody
	public Map<String, Object> doLogin(Model model,HttpServletRequest request,ParamPoAdmin paramPo
			,@RequestParam(defaultValue="1")int page){
		
		String userName=(String)request.getParameter("user");
		String pwd=(String)request.getParameter("pwd");
		
		if(userName!=null&&pwd!=null){
			SysUser admin=systemServiceImpl.selectByUserName(userName);
			 if(admin!=null&&admin.getPwd().equals(Md5Util.MD5(pwd))){
				 SysRole role=systemServiceImpl.selectRoleById(admin.getRoleId());
				 admin.setLoginTime(TimeManager.currentTime());
				 admin.setLoginCount(admin.getLoginCount()+1);
				 PageData pd=new PageData();
				 pd.put("userId", admin.getUserId());
				 systemServiceImpl.updateUser(  admin);
				 request.getSession().setAttribute("role",role);
				 request.getSession().setAttribute("user",admin);
				 return getSuccessMap();
			 }
		}
		return getErrorMap("用户名密码不匹配!");
	}
 
}
